<?php
require 'config.php';

$shortCode = '';
$message = '';
$shortUrl = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['original_url'])) {
    $originalUrl = trim($_POST['original_url']);

    // 验证URL有效性
    if (filter_var($originalUrl, FILTER_VALIDATE_URL)) {
        // 生成6位短码
        $shortCode = substr(md5(uniqid()), 0, 6);

        // 检查短码是否已存在
        $stmt = $pdo->prepare("SELECT id FROM short_urls WHERE short_code = :short_code");
        $stmt->execute([':short_code' => $shortCode]);
        
        // 如果短码已存在，重新生成
        if ($stmt->fetch()) {
            $shortCode = substr(md5(uniqid(mt_rand(), true)), 0, 6);
        }

        // 保存到数据库
        $stmt = $pdo->prepare("INSERT INTO short_urls (short_code, original_url, created_at) VALUES (:short_code, :original_url, NOW())");
        $stmt->execute([
            ':short_code' => $shortCode,
            ':original_url' => $originalUrl
        ]);

        // 自动获取当前域名和协议
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $domain = $_SERVER['HTTP_HOST'];
        $shortUrl = $protocol . '://' . $domain . '/redirect.php?code=' . $shortCode;
        
        $message = "短链已生成：<a href='$shortUrl' target='_blank'>$shortUrl</a>";
    } else {
        $message = "<span style='color: red;'>请输入有效的 URL，例如：https://example.com</span>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>短链接生成器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            text-align: center;
        }
        .container {
            margin-top: 50px;
        }
        input[type="text"] {
            width: 70%;
            padding: 10px;
            margin: 10px 0;
            font-size: 16px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>短链接生成器</h2>
        <p>输入长网址，生成简短易分享的链接</p>
        
        <form method="post">
            <input type="text" name="original_url" placeholder="https://example.com/long-url-path" 
                   size="50" required value="<?= isset($_POST['original_url']) ? htmlspecialchars($_POST['original_url']) : '' ?>" />
            <br>
            <button type="submit">生成短链接</button>
        </form>

        <?php if ($message): ?>
            <div class="result">
                <?= $message ?>
                <?php if ($shortUrl): ?>
                    <p style="margin-top: 10px;">
                        <button onclick="copyToClipboard('<?= htmlspecialchars($shortUrl) ?>')">复制短链接</button>
                    </p>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // 复制到剪贴板功能
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                alert('短链接已复制到剪贴板！');
            }, function() {
                alert('复制失败，请手动复制。');
            });
        }
    </script>
</body>
</html>
